package org.demo.base.jdbc;

import com.mysql.jdbc.Driver;
import org.apache.commons.dbutils.QueryRunner;
import org.demo.base.jdbc.util.TXQueryRunner;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


/**
 *  Statement 一次连接数据库有一个就可以，可以执行多个sql
 */
public class AccountDao {

    public void transfer(){
        Connection connection = null;
        Statement statement = null;
        try {
            DriverManager.registerDriver(new Driver());
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/zhaofei","root","root");
            connection.setAutoCommit(false);
            statement = connection.createStatement();
            String sql1 = "update account set money=money-100 where name='aaa'";
            String sql2 = "update account set money=money+100 where name='bbb'";
            int update1 = statement.executeUpdate(sql1);
            int update2 = statement.executeUpdate(sql2);
            System.out.println("transfer1:update1:"+update1);
            System.out.println("transfer1:update2:"+update2);
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(statement!=null) {
                    statement.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public void update(String name,double balance) throws SQLException {
        QueryRunner queryRunner = new TXQueryRunner();
        String sql = "update account set money=money+? where name=?";
        Object[] params = {balance,name};
        queryRunner.update(sql,params);
    }

}
